<?php


namespace app\validate;


use think\Validate;

class GoodsValidate extends Validate
{
    protected $rule = [
        'id' => 'require',
        'goods_name' => 'require|maxName',
        'category_id' => 'require',
        'goods_image' => 'require',
        'goods_price' => 'require|egt:0',
//        'goods_stock' => 'require|egt:0',
        'goods_banner' => 'require',
        'goods_detail' => 'require',
        'goods_sku' => 'require'
    ];


    protected $message = [
        'id.require' => 'id不能为空',
        'name.require' => '商品名称不能为空',
//        'category_id.require' => '分类不能为空',
        'image.require' => '商品主图不能为空',
        'market_price.require' => '价格不能为空',
        'market_price.egt' => '价格必须大于等于0',
        'sell_price.require' => '价格不能为空',
        'sell_price.egt' => '价格必须大于等于0',
        'stock.require' => '库存不能为空',
        'stock.egt' => '库存必须大于等于0',
        'banner.require' => '商品轮播图片不能为空',
        'detail.require' => '商品详情图不能为空',
        'goods_sku.require' => '请设置规格',
    ];

    protected $scene = [
        'add' => ['name', 'image', 'market_price', 'sell_price', 'stock', 'banner', 'detail', 'goods_sku'],
        'edit' => ['id', 'name', 'image', 'market_price', 'sell_price', 'stock', 'banner', 'detail', 'goods_sku'],
    ];

    protected function maxName($value)
    {
        $len = mb_strlen($value, 'UTF8');
        if ($len <= 50) {
            return true;
        }
        return '商品名称长度超过限制';
    }

    protected function validShowContext($value, $rule, $data)
    {
        if ($data['show_discount'] == 1 && !$data['discount_text']) {
            return '优惠文案不能为空';
        }
        return true;
    }

    protected function validPrice($value, $rule, $data)
    {
        // show_discount = 1开启活动  2未开启
        if ($data['show_discount'] == 1 && isset($data['original_price']) && $data['original_price'] <= 0) {
            if (!isset($data['original_price'])) {
                return '原价不能为空';
            }
            if ($data['original_price'] <= 0) {
                return '原价必须大于0';
            }
            return true;
        } else {
            if (!isset($data['original_price'])) {
                return true;
            }
            if ($data['original_price'] > 0 && $data['original_price'] <= $data['price']) {
                return '原价必须大于优惠价';
            }
            return true;
        }
    }
}